"""
区域管理Schema模型
用于接口请求和响应的数据结构定义
对应数据库表: base_region_province, base_region_city, base_region_area
"""
from datetime import datetime
from typing import Optional, List

from pydantic import BaseModel, Field, ConfigDict, validator


class RegionBase(BaseModel):
    """区域基础模型"""
    code: str = Field(..., description="国标6位编码，不足位补零", max_length=6, min_length=6)
    name: str = Field(..., description="区域名称", max_length=64)
    level: int = Field(..., description="层级：1=省，2=市，3=区县", ge=1, le=3)

    @validator('code')
    def validate_code_format(cls, v):
        """验证区域编码格式"""
        if not v or not v.strip():
            raise ValueError("区域编码不能为空")
        v = v.strip()
        if len(v) != 6:
            raise ValueError("区域编码必须为6位")
        if not v.isdigit():
            raise ValueError("区域编码只能包含数字")
        return v

    @validator('name')
    def validate_name_format(cls, v):
        """验证区域名称格式"""
        if not v or not v.strip():
            raise ValueError("区域名称不能为空")
        return v.strip()


class ProvinceOut(RegionBase):
    """省份输出模型"""
    id: int = Field(..., description="主键ID")
    level: int = Field(1, description="层级：1=省")
    gmt_create: datetime = Field(..., description="创建时间")
    gmt_update: datetime = Field(..., description="更新时间")

    model_config = ConfigDict(from_attributes=True)


class CityOut(RegionBase):
    """城市输出模型"""
    id: int = Field(..., description="主键ID")
    province_code: str = Field(..., description="所属省份编码", max_length=6)
    level: int = Field(2, description="层级：2=市")
    gmt_create: datetime = Field(..., description="创建时间")
    gmt_update: datetime = Field(..., description="更新时间")

    model_config = ConfigDict(from_attributes=True)


class AreaOut(RegionBase):
    """区县输出模型"""
    id: int = Field(..., description="主键ID")
    city_code: str = Field(..., description="所属城市编码", max_length=6)
    level: int = Field(3, description="层级：3=区县")
    gmt_create: datetime = Field(..., description="创建时间")
    gmt_update: datetime = Field(..., description="更新时间")

    model_config = ConfigDict(from_attributes=True)


class RegionTreeNode(BaseModel):
    """区域树节点模型"""
    code: str = Field(..., description="区域编码")
    name: str = Field(..., description="区域名称")
    level: int = Field(..., description="层级：1=省，2=市，3=区县")
    children: Optional[List['RegionTreeNode']] = Field(default_factory=list, description="子区域列表")

    model_config = ConfigDict(from_attributes=True)


class RegionTree(BaseModel):
    """完整区域树结构"""
    provinces: List[RegionTreeNode] = Field(default_factory=list, description="省份列表")

    model_config = ConfigDict(from_attributes=True)


class RegionQuery(BaseModel):
    """区域查询参数"""
    keyword: Optional[str] = Field(None, description="关键字搜索", max_length=64)
    level: Optional[int] = Field(None, description="层级过滤：1=省，2=市，3=区县", ge=1, le=3)


# 让Pydantic正确处理自引用
RegionTreeNode.model_rebuild()